package net.inxweb.bluemeerkat.infra.jcr.modeshap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.modeshape.graph.SecurityContext;
import org.modeshape.jcr.JcrConfiguration;
import org.modeshape.jcr.JcrEngine;
import org.modeshape.jcr.JcrRepository;
import org.modeshape.jcr.SecurityContextCredentials;
import org.xml.sax.SAXException;

public class Test {

	/**
	 * @param args
	 * @throws SAXException 
	 * @throws IOException 
	 */
	public static void main(String[] args)  {
		JcrConfiguration configuration = new JcrConfiguration();
		
		try { 
			configuration.loadFrom("C:/kbm_framework/workspace/maven.1270789596917/trunk/bluemeerkat-infra/bluemeerkat-jcr-infra/bluemeerkat-modeshap-jcr-infra/src/main/resources/configRepository.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();  
			return;
		} 
 
		// Now create the JCR engine ...
		JcrEngine engine = configuration.build();
		
		engine.start();
		
		engine.getRepositorySource("sample");
		
		JcrRepository repository;
		try {
			repository = engine.getRepository("sample");
		} catch (RepositoryException e) { 
			e.printStackTrace();
			return;
		}

		
        SecurityContext securityContext = new CustomSecurityContext();
        SecurityContextCredentials credentials = new SecurityContextCredentials(securityContext); 
		Session session = null;
		try {
			session = repository.login(credentials);
 
			 
			Node rootNode = session.getRootNode();  
			
			Node folder = rootNode.getNode("folder1");
		 
			File file = new File("c:/", "/jars-info.txt");   
			
			Node fileNode = folder.addNode(file.getName(), "nt:file");   
			
			
			
			Node resourceNode = fileNode.addNode("jcr:content", "nt:resource");  
			
			resourceNode = fileNode.getNode("jcr:content"); 
			resourceNode.setProperty("jcr:mimeType", "text/html");
			resourceNode.setProperty("jcr:encoding", ""); 
			resourceNode.setProperty("jcr:data", new FileInputStream(file));  
	 
			Calendar lastModified = Calendar.getInstance(); 
			resourceNode.setProperty("jcr:lastModified", lastModified);  
		 
			session.save(); 
			
		} catch (RepositoryException e) { 
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally { 
			session.logout(); 
			engine.shutdown();  
		}
		 


		


	} 
}
